<template>
	<view class="body">
		<input password v-model="oldPassword" class="uni-input" placeholder="请输入旧密码 (6-16个字母、数字、下划线)" />
		<input password v-model="newPassword1" class="uni-input" placeholder="请输入新密码 (6-16个字母、数字、下划线)" />
		<input password v-model="newPassword2" class="uni-input" placeholder="请确认新密码 (6-16个字母、数字、下划线)" />
		<button class="confirm" :class="{'active': disable()}" hover-class="button-hover" @tap="submit">确认修改</button>
	</view>
</template>

<script>
	import * as userApi from "network/user.js"
	export default {
		data() {
			return {
				oldPassword: "",
				newPassword1: "",
				newPassword2: "",
				patrn: /^(\w){6,16}$/
			};
		},
		methods: {
			// 是否可以提交
			disable() {
				return this.oldPassword.trim() && this.newPassword1.trim() && this.newPassword2.trim()
			},
			// 验证层
			check() {
				if (!this.disable()) {
					return false
				}
				let errText = null
				// 验证原密码
				if (this.patrn.exec(this.oldPassword)) {
					// 验证两个密码是否相同
					if (this.newPassword1 === this.newPassword2) {
						// 验证密码是否合格
						if (this.patrn.exec(this.newPassword1)) {
							return true
						} else {
							errText = "新密码格式不正确"
						}
					} else {
						errText = "两次输入密码不一致"
					}
				} else {
					errText = "原密码不正确"
				}
				// 显示错误
				if (errText) {
					uni.showToast({
						title: errText,
						icon: "none"
					})
					return false
				}
			},
			// 提交
			async submit() {
				if (!this.check()) {
					return
				}
				uni.showToast({
					title: "正在修改",
					icon: "loading",
					mask: true
				})
				const res = await userApi.updatePassword(this.oldPassword, this.newPassword1)
				if(res.meta.code === 200){
					uni.showToast({
						title: "修改成功",
						icon: "none"
					})
					this.$Router.back()
				}else{
					uni.showToast({
						title: res.meta.message,
						icon: "none"
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.body {
		padding: 0 30upx;
		overflow: hidden;

		.uni-input {
			margin: 23upx auto;
			width: 90%;
			border-bottom: 1upx solid #DDDDDD;
		}

		.confirm {
			margin-top: 50upx !important;
			width: 100%;
			margin: 20upx 0;
			font-size: 38upx;
			color: #909090;
			background-color: #DDDDDD;

			&.active {
				color: #333333;
				background-color: #FFE933;

				&.button-hover {
					background-color: #cab528;
				}
			}
		}
	}
</style>
